// API基础配置
export const baseUrl = "http://192.168.2.184";

// API URL配置
const API_URLS = {
    WX_LOGIN: "/user/wx/login",
    REGISTER: "/user/register",
    CLASS_CHECKIN_HISTORY: "/checkinhistory/checkinhistorylist",
    ADD_CHECKIN_HISTORY: "/checkinhistory/addcheckinhistory",
    CHECKIN_RECORD_LIST: "/checkinrecord/checkinrecordlist",
    STUDENT_CHECKIN_BY_HISTORY: "/checkinhistory/students",
    UPDATE_CHECKIN_STATE: "/checkinrecord/update",
    STUDENT_CHECKIN_RECORDS: "/checkinrecord/records",
    CLASS_LIST_BY_COURSE: "/class/classlist",
    ADD_CLASS: "/class/addclass",
    UPDATE_CLASS: "/class/update",
    DELETE_CLASS: "/class/delete",
    STUDENT_CLASS_LIST: "/class/classlist",
    TEACHER_COURSE_LIST: "/course/courselist",
    ADD_COURSE: "/course/addcourse",
    COURSE_DETAIL: "/course",
    UPDATE_COURSE: "/course/update",
    DELETE_COURSE: "/course/delete",
    STUDENT_COURSE_LIST: "/course/student/courselist",
    STUDENTS_BY_CLASS_ID: "/user/students",
    STUDENT_UPCOMING_CHECKIN: "/student/checkin/upcoming",
    STUDENT_COURSES_WITH_STATS: "/student/courses",
    STUDENT_COURSE_CHECKIN_RECORDS: "/student/checkin/course",
    STUDENT_SIGNIN: "/student/signin",
    VIDEO_CHECKIN: "/student/video/signin",
    JOIN_CLASS: "/student/join-class",
};

// 通用请求方法
function request(url, method, data) {
    return new Promise((resolve, reject) => {
        wx.request({
            url: `${baseUrl}${url}`,
            method,
            data,
            success: (res) => {
                if (res.data.code === 200) {
                    resolve(res.data);
                } else {
                    reject(res.data);
                }
            },
            fail: (err) => {
                // 抛出
                console.log(err);

                reject(err);
            },
        });
    });
}

// 具体API方法
export const wxLogin = (code) => {
    return request(API_URLS.WX_LOGIN, "POST", { code });
};

export const registerUser = (userId, name, role) => {
    return request(API_URLS.REGISTER, "POST", { userId, name, role });
};

// 其他API方法可以继续添加...

export const getClassCheckinHistory = (classId) => {
    return request(`${API_URLS.CLASS_CHECKIN_HISTORY}/${classId}`, "GET");
};

export const addCheckinHistory = (
    clazzId,
    historyName = "",
    durationInMinutes = 5
) => {
    return request(API_URLS.ADD_CHECKIN_HISTORY, "POST", {
        clazzId,
        historyName,
        durationInMinutes,
    });
};

export const getCheckinRecordList = (checkinHistoryId) => {
    return request(`${API_URLS.CHECKIN_RECORD_LIST}/${checkinHistoryId}`, "GET");
};

export const updateCheckinState = (
    userId,
    newCheckinStateId,
    checkinHistoryId
) => {
    return request(API_URLS.UPDATE_CHECKIN_STATE, "PUT", {
        userId,
        newCheckinStateId,
        checkinHistoryId,
    });
};

export const getStudentCheckinRecords = (studentId, classId) => {
    return request(
        `${API_URLS.STUDENT_CHECKIN_RECORDS}/${studentId}/${classId}`,
        "GET"
    );
};

export const getClassListByCourse = (courseId) => {
    return request(`${API_URLS.CLASS_LIST_BY_COURSE}/${courseId}`, "GET");
};

export const addClass = (className, courseId) => {
    return request(API_URLS.ADD_CLASS, "POST", {
        className,
        course: { id: courseId },
    });
};

export const updateClass = (id, name, classCode) => {
    return request(API_URLS.UPDATE_CLASS, "PUT", { id, name, classCode });
};

export const deleteClass = (classId) => {
    return request(`${API_URLS.DELETE_CLASS}/${classId}`, "DELETE");
};

export const joinClass = (studentId, classCode) => {
    return request(API_URLS.JOIN_CLASS, "POST", { studentId, classCode });
};

export const getStudentClassList = (studentId, courseId) => {
    return request(
        `${API_URLS.STUDENT_CLASS_LIST}/${studentId}/${courseId}`,
        "GET"
    );
};

export const getTeacherCourseList = (teacherId) => {
    return request(`${API_URLS.TEACHER_COURSE_LIST}/${teacherId}`, "GET");
};

export const addCourse = (courseName, teacherId) => {
    return request(API_URLS.ADD_COURSE, "POST", {
        courseName,
        teacherId,
    });
};

export const getCourseDetail = (id) => {
    return request(`${API_URLS.COURSE_DETAIL}/${id}`, "GET");
};

export const updateCourse = (id, name, teacherId) => {
    return request(API_URLS.UPDATE_COURSE, "PUT", { id, name, teacherId });
};

export const deleteCourse = (id) => {
    return request(`${API_URLS.DELETE_COURSE}/${id}`, "DELETE");
};

export const getStudentCourseList = (studentId) => {
    return request(`${API_URLS.STUDENT_COURSE_LIST}/${studentId}`, "GET");
};

/**
 * 获取学生课程列表（包含签到统计信息）
 * @param {string} studentId 学生ID
 * @returns {Promise} 学生课程列表，包含每门课程的签到统计信息
 */
export const getStudentCoursesWithStats = (studentId) => {
    return request(`${API_URLS.STUDENT_COURSES_WITH_STATS}/${studentId}`, "GET");
};

export const getStudentsByClassId = (classId) => {
    return request(`${API_URLS.STUDENTS_BY_CLASS_ID}/${classId}`, "GET");
};

/**
 * 获取指定签到下所有学生的签到情况
 * @param {string} checkinHistoryId 签到历史ID
 * @returns {Promise} 学生签到情况列表
 */
export const getStudentCheckinByHistoryId = (checkinHistoryId) => {
    return request(
        `${API_URLS.STUDENT_CHECKIN_BY_HISTORY}/${checkinHistoryId}`,
        "GET"
    );
};

/**
 * 获取学生最近需要签到的信息
 * @param {string} studentId 学生ID
 * @returns {Promise} 最近需要签到的信息
 */
export const getStudentUpcomingCheckin = (studentId) => {
    return request(`${API_URLS.STUDENT_UPCOMING_CHECKIN}/${studentId}`, "GET");
};

/**
 * 图片上传接口
 * @param {Object} options - 上传参数
 * @param {File|String} options.file - 文件对象或文件路径
 * @param {String} options.type - 图片用途类型，如 'face' 表示人脸图片
 * @param {String} options.userId - 用户ID
 * @param {Function} options.success - 上传成功回调
 * @param {Function} options.fail - 上传失败回调
 * @param {Function} options.complete - 上传完成回调（无论成功失败）
 */
export const uploadImage = (options = {}) => {
    const { file, type = "common", success, fail, complete, userId } = options;
    console.log("上传图片", file, type, userId);

    // 使用小程序的上传文件API
    return wx.uploadFile({
        url: `${baseUrl}/upload/face`,
        filePath: file, // 要上传文件资源的路径（本地路径）
        name: "file", // 文件对应的 key，后端通过这个 key 获取文件
        formData: {
            // HTTP 请求中其他额外的 form data
            type: type,
            userId: userId,
            timestamp: new Date().getTime(),
        },
        success: (res) => {
            // 上传成功
            let data;
            try {
                // 解析返回的JSON数据
                data = JSON.parse(res.data);
                if (data.code === 200) {
                    // 成功回调
                    typeof success === "function" && success(data.data);
                } else {
                    // 业务逻辑错误
                    typeof fail === "function" &&
                        fail({
                            errCode: data.code,
                            errMsg: data.message || "上传失败",
                        });
                }
            } catch (e) {
                // JSON解析出错
                typeof fail === "function" &&
                    fail({
                        errCode: -1,
                        errMsg: "服务器返回数据格式错误",
                    });
            }
        },
        fail: (err) => {
            // 网络或其他错误
            typeof fail === "function" &&
                fail({
                    errCode: err.errCode || -1,
                    errMsg: err.errMsg || "网络错误，上传失败",
                });
        },
        complete: (res) => {
            // 完成回调
            typeof complete === "function" && complete(res);
        },
    });
};

/**
 * 获取学生在指定课程中的签到记录
 * @param {string} studentId 学生ID
 * @param {string} courseId 课程ID
 * @returns {Promise} 学生在指定课程中的签到记录列表
 */
export const getStudentCourseCheckinRecords = (studentId, classId) => {
    return request(
        `${API_URLS.STUDENT_COURSE_CHECKIN_RECORDS}/${studentId}/${classId}`,
        "GET"
    );
};

/**
 * 学生签到接口
 * @param {number|string} studentId 学生ID
 * @param {number|string} checkinHistoryId 签到历史记录ID
 * @returns {Promise} 签到结果
 */
export const studentSignin = (studentId, checkinHistoryId) => {
    return request(API_URLS.STUDENT_SIGNIN, "POST", {
        studentId,
        checkinHistoryId
    });
};